#!/bin/sh

echo "+++++ Excuting establish_trust.sh +++++"
cn_ip=`cat config.txt | sed '/^CN_IP=/!d;s/.*=//'`
worker_ip=`cat config.txt | sed '/^WORKER_IP=/!d;s/.*=//'`
worker_ip+=" $cn_ip"
username=root

#check the network of worker node
checkNetwork()
{
    echo "check network..."
    flag=0
    for i in $worker_ip
    do
        ping -c 1 $i >/dev/null
        if [ $? -eq 0 ];then
            echo -n 
        else
            echo "$i: The network is not ok."
            flag=$(($flag+1))
        fi
    done
    if [ $flag -gt 0 ]; then
        echo "pls check your network."
        exit 1
    fi
}

establishTrust()
{
    echo "Check password free login..."
    if [ ! -f ~/.ssh/id_rsa.pub -o ! -f ~/.ssh/id_rsa.pub ]
    then
        expect -c "
        spawn ssh-keygen -t rsa
        expect {
            \"*.ssh/id_rsa*\" {send \"\r\";exp_continue}
            \"*passphrase*\" {send \"\r\";exp_continue}
            \"*passphrase again*\" {send \"\r\";}
         }"

    else
        echo "The id_rsa.pub has been generated."
    fi

    for ip in $worker_ip
    do
        ssh -o PreferredAuthentications=publickey -o StrictHostKeyChecking=no $username@$ip date >/dev/null 2>&1
        if [ $? -eq 0 ]
        then
            echo -n
        else
            IFS_OLD=$IFS
            IFS=
            echo "Type Password!"
            read -p "pls input password for establist trust $ip:" -s password
            IFS=$IFS_OLD
            expect -c "
            spawn ssh-copy-id $username@$ip
            expect {
　　            \"*yes/no*\" {send \"yes\r\"; exp_continue}
　　            \"*assword:\" {send \"$password\r\"; exp_continue}
                \"*ermission denied*\" {send \"123456789\r\";}
　　        }"
        fi
    
    done
}   
checkNetwork
establishTrust 
